package com.all.security.service;

import com.all.security.model.entity.SysUserDetails;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author
 * @ClassName SecurityUserDetailsService
 * @Date 2024/3/31 15:06
 * @Description SecurityUserDetailsService
 * @Version 1.0
 */
@Slf4j
public class SecurityUserDetailsService implements UserDetailsService {

    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private ISysUserService iSysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("登录用户：{}", username);
        try {
            SysUserDetails user = iSysUserService.buildSysUserDetails(username);
            log.info("登录用户信息：{}", user);
            return user;
        } catch (Exception e) {
            String msg = "Username: " + username + " not found";
            log.error(msg, e);
            throw new UsernameNotFoundException(msg);
        }
    }

    /**
     * 测试用户信息
     */
    public SysUserDetails getAuthorities(String username){
        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("ADMIN"));
        authorities.add(new SimpleGrantedAuthority("ADMIN2"));
        authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN2"));
        SysUserDetails user = new SysUserDetails(1L, username, "admin",
                passwordEncoder.encode("123456"), authorities,
                true, true, true, true);
        return user;
    }
}
